package per.turtle.job.controller;

import cn.hutool.core.util.StrUtil;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.quartz.CronExpression;
import org.quartz.SchedulerException;
import org.springframework.web.bind.annotation.*;
import per.turtle.common.core.constant.CommonConstants;
import per.turtle.common.core.exception.job.TaskException;
import per.turtle.common.core.web.controller.BaseController;
import per.turtle.common.core.web.entity.CommonResult;
import per.turtle.common.core.web.page.TableDataInfo;
import per.turtle.common.excel.annotation.ResponseExcel;
import per.turtle.common.log.annotation.Log;
import per.turtle.common.log.enums.BusinessType;
import per.turtle.common.security.annotation.PreAuthorize;
import per.turtle.common.security.service.TokenService;
import per.turtle.job.domain.SysJob;
import per.turtle.job.service.ISysJobService;
import per.turtle.job.util.ScheduleUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 调度任务信息操作处理
 *
 * @author turtle
 */
@RequestMapping("job")
@RequiredArgsConstructor
@RestController
public class SysJobController extends BaseController {

    private final ISysJobService jobService;

    private final TokenService tokenService;

    @Operation(summary = "新增定时任务", description = "新增定时任务")
    @Log(title = "定时任务", businessType = BusinessType.INSERT)
    @PostMapping
    @PreAuthorize(hasPermission = "monitor:job:add")
    public CommonResult<Void> add(@RequestBody SysJob job) throws SchedulerException, TaskException {
        if (!CronExpression.isValidExpression(job.getCronExpression())) {
            return CommonResult.error("新增任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        } else if (StrUtil.containsIgnoreCase(job.getInvokeClass() + job.getInvokeMethod(), CommonConstants.LOOKUP_RMI)) {
            return CommonResult.error("新增任务'" + job.getJobName() + "'失败，不允许`rmi`调用");
        } else if (StrUtil.containsAnyIgnoreCase(job.getInvokeClass() + job.getInvokeMethod(),
                                                 new String[]{CommonConstants.LOOKUP_LDAP, CommonConstants.LOOKUP_LDAPS})) {
            return CommonResult.error("新增任务'" + job.getJobName() + "'失败，目标字符串不允许`ldap(s)`调用");
        } else if (StrUtil.containsAnyIgnoreCase(job.getInvokeClass() + job.getInvokeMethod(), new String[]{CommonConstants.HTTP, CommonConstants.HTTPS})) {
            return CommonResult.error("新增任务'" + job.getJobName() + "'失败，不允许`http(s)`调用");
        } else if (StrUtil.containsAnyIgnoreCase(job.getInvokeClass() + job.getInvokeMethod(), CommonConstants.JOB_ERROR_STR)) {
            return CommonResult.error("新增任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        } else if (!ScheduleUtils.whiteList(job.getInvokeClass() + job.getInvokeMethod())) {
            return CommonResult.error("新增任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        return result(jobService.insertJob(job));
    }

    @Operation(summary = "定时任务状态修改", description = "定时任务状态修改")
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @PreAuthorize(hasPermission = "monitor:job:changeStatus")
    @PutMapping("changeStatus")
    public CommonResult<Void> changeStatus(@RequestBody SysJob job) throws SchedulerException {
        SysJob newJob = jobService.selectJobById(job.getJobId());
        newJob.setIsDisabled(job.getIsDisabled());
        return result(jobService.changeStatus(newJob));
    }

    @Operation(summary = "修改定时任务", description = "修改定时任务")
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @PreAuthorize(hasPermission = "monitor:job:edit")
    @PutMapping
    public CommonResult<Void> edit(@RequestBody SysJob sysJob) throws SchedulerException, TaskException {
        if (!CronExpression.isValidExpression(sysJob.getCronExpression())) {
            return CommonResult.error("cron表达式不正确");
        }
        return result(jobService.updateJob(sysJob));
    }

    @Operation(summary = "导出定时任务列表", description = "导出定时任务列表")
    @Log(title = "定时任务", businessType = BusinessType.EXPORT)
    @PostMapping("export")
    @PreAuthorize(hasPermission = "monitor:job:export")
    @ResponseExcel("定时任务")
    public List<SysJob> export(HttpServletResponse response, @RequestBody SysJob sysJob) {
        return jobService.selectJobList(sysJob);
    }

    @Operation(summary = "获取定时任务详细信息", description = "获取定时任务详细信息")
    @GetMapping("{jobId}")
    @PreAuthorize(hasPermission = "monitor:job:query")
    public CommonResult<SysJob> getInfo(@PathVariable("jobId") Long jobId) {
        return CommonResult.success(jobService.selectJobById(jobId));
    }

    @Operation(summary = "查询定时任务列表", description = "查询定时任务列表")
    @PostMapping("list")
    @PreAuthorize(hasPermission = "monitor:job:list")
    public TableDataInfo<SysJob> list(@RequestBody SysJob sysJob) {
        List<SysJob> list = startPage(s -> jobService.selectJobList(sysJob));
        return getDataTable(list);
    }

    @Operation(summary = "删除定时任务", description = "删除定时任务")
    @DeleteMapping("{jobIds}")
    @Log(title = "定时任务", businessType = BusinessType.DELETE)
    @PreAuthorize(hasPermission = "monitor:job:remove")
    public CommonResult<Void> remove(@PathVariable Long[] jobIds) throws SchedulerException {
        jobService.deleteJobByIds(jobIds);
        return CommonResult.success();
    }

    @Operation(summary = "定时任务立即执行一次", description = "定时任务立即执行一次")
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @PreAuthorize(hasPermission = "monitor:job:changeStatus")
    @PutMapping("run")
    public CommonResult<Void> run(@RequestBody SysJob job) throws SchedulerException {
        jobService.run(job);
        return CommonResult.success();
    }

}
